package biz.appframe;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.rfid.project.exception.CannotDelException;

@Controller
public class AppController {

	private static final Logger logger = LoggerFactory.getLogger(AppController.class);

	@Autowired
	private MenuService menuService;

	@Autowired
	private ModuleService moduleService;
	
	/****************************** 用户信息处理  ***************************/
	/*
	@RequestMapping(value = "/")
	public String login(HttpServletRequest request) {
		return "login";
	}
	*/
	
	//@RequestMapping(value = "/index")
	@RequestMapping(value = "/")
	public String welcom(HttpServletRequest request, HttpServletResponse response, Model model) {
		/*
		List<Module> modules = moduleService.findAll();
		List<Menu> menus = menuService.findAll();
		StringBuilder menuTree = new StringBuilder();
		menuTree.append("{'menus':[");
		int menuIndex = 1;
		for(Module module:modules){
			menuTree.append("{'menuid':'"+(menuIndex++)+"','icon':'icon-sys','menuname':'"+module.getName()+"',");
			menuTree.append(			"'menus':[");
			for(Menu menu : menus){
				if(menu.getModuleCode().equals(module.getModuleCode())){
					menuTree.append("{'menuname':'"+menu.getName()+"','icon':'icon-nav','url':'"+menu.getCode()+"'},");
				}
				
			}
			menuTree.append("]},");
		}
		menuTree.append("]}");
		
		String menuStr = menuTree.toString().replace("'", "\"");
		System.out.println(menuStr);
		model.addAttribute("menuStr", menuStr);
		*/
		return "login";
	}
	@RequestMapping(value = "/index")
	public String index() {
		return "index";
	}
	/***********************************  模块管理  ********************************************/
	@RequestMapping(value = "/modelmgr")
	public String toModel(HttpServletRequest request, HttpServletResponse response) {
		return "modelmgr";
	}
	
	@RequestMapping(value = "/queryModule")
	public String queryModule(HttpServletRequest request, HttpServletResponse response) {
		List<Module> modules = moduleService.findAll();
		JSONObject object = new JSONObject();
		object.put("total", modules.size());
		
		JSONArray models = new JSONArray();
		for (Module module : modules) {
			JSONObject mod = new JSONObject();
			wrapModulData(module, mod);
			
			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	@RequestMapping(value = "/findModule")
	public String findModule(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		Module module = moduleService.findOne(id);
		JSONObject object = new JSONObject();
		JSONObject mod = new JSONObject();
		wrapModulData(module, mod);
		object.put("success", true);
		object.put("data", mod);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	private void wrapModulData(Module module, JSONObject mod) {
		mod.put("id", module.getId());
		mod.put("name", module.getName());
		mod.put("orderNumber", module.getOrderNumber());
		mod.put("moduleCode", module.getModuleCode());
		String content = module.getRemark();
		mod.put("remark", content == null ? "" : content);
	}

	@RequestMapping(value = "/editModule")
	public String editModule(HttpServletRequest request,
			HttpServletResponse response, @Valid Module module,
			Model model, RedirectAttributes redirectAttributes) {
		this.moduleService.save(module);
		
		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delModule")
	public String delModule(
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			this.moduleService.delete(id);
		} catch (CannotDelException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/modulChangeOrderNumber")
	public String changeOrderNumber(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id,
			@RequestParam(value = "targetId", defaultValue = "") Long targetId){
		JSONObject result = new JSONObject();
		boolean flag = this.moduleService.changeOrderNumber(id, targetId);
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	/**************************************  菜单管理   ************************************************/
	@RequestMapping(value = "/menumgr")
	public String menumgr(HttpServletRequest request, HttpServletResponse response, Model model) {
		List<Module> modules = moduleService.findAll();
		model.addAttribute("modules", modules);
		return "menumgr";
	}
	
	@RequestMapping(value = "/queryMenu")
	public String queryMenu(
			HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam(value = "moduleCode", defaultValue = "") String moduleCode,
			@RequestParam(value = "menuName", defaultValue = "") String menuName,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "20") Integer pageSize) {
		List<Module> modules = moduleService.findAll();
		Page<Menu> menus = menuService.findAll(moduleCode, menuName, pageNumber, pageSize);
		
		JSONObject object = new JSONObject();
		object.put("total", menus.getTotalElements());
		JSONArray models = new JSONArray();
		for (Menu menu : menus) {
			JSONObject mod = new JSONObject();
			wrapData(modules, menu, mod);
			
			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}

	@RequestMapping(value = "/findMenu")
	public String findMenu(
			HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		List<Module> modules = moduleService.findAll();
		Menu menu = menuService.findOne(id);
		JSONObject object = new JSONObject();
		JSONObject mod = new JSONObject();
		wrapData(modules, menu, mod);
		object.put("success", true);
		object.put("data", mod);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	private void wrapData(List<Module> modules, Menu menu, JSONObject mod) {
		mod.put("id", menu.getId());
		mod.put("name", menu.getName());
		mod.put("code", menu.getCode());
		String remark = menu.getRemark();
		mod.put("remark", remark == null?"":remark);
		mod.put("moduleCode", menu.getModuleCode());
		mod.put("moduleName", findModuleByMenu(modules, menu).getName());
	}
	
	private Module findModuleByMenu(List<Module> modules, Menu menu){
		for (Module module : modules) {
			if (module.getModuleCode().equals(menu.getModuleCode())) {
				return module;
			}
		}
		return null;
	}

	@RequestMapping(value = "/editMenu")
	public String editMenu(HttpServletRequest request,
			HttpServletResponse response, @Valid Menu menu,
			Model model, RedirectAttributes redirectAttributes) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			this.menuService.save(menu);
		} catch (CannotDelException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delMenu")
	public String delMenu(
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		this.menuService.delete(id);

		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	//验证Menu
	@RequestMapping(value = "/validateMenu")
	public String validateMenu(HttpServletRequest request,
			HttpServletResponse response, @Valid Menu menu,
			Model model, RedirectAttributes redirectAttributes) {
		Page<Menu> menus = menuService.findAll(menu.getModuleCode(), menu.getName(), 1, 20);
		JSONObject result = new JSONObject();
		result.put("count", menus.getTotalElements());
		PageJsonBean.printObject(response, result);
		return null;
	}
}

